package com.lancoo.znbkxx.teacher.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;


import com.facebook.rebound.BuildConfig;
import com.lancoo.znbkxx.teacher.R;
import com.lancoo.znbkxx.teacher.utils.DensityUtils;

import java.math.BigDecimal;


/**
 * Created by Dadong on 2020/8/17
 * Describe:
 */
public class CircleProgress extends View {
    private static final String TAG = CircleProgress.class.getSimpleName();
    private Context mContext;

    private int mDefaultSize;
    //是否开启抗锯齿
    private boolean antiAlias;
    //绘制背景
    private Paint mBgPaint;
    //绘制单位
    private TextPaint mUnitPaint;
    private CharSequence mUnit;
    private int mUnitColor;
    private float mUnitSize;
    private float mUnitOffset;

    //绘制数值
    private TextPaint mValuePaint;
    private float mValue;
    private float mMaxValue;
    private float mValueOffset;
    private int mPrecision;
    private String mPrecisionFormat;
    private int mValueColor;
    private float mValueSize;

    //绘制圆弧
    private Paint mArrowPaint;
    private int mBgArrowColor;
    private Paint mArcPaint;
    private float mArcWidth;
    private float mStartAngle, mSweepAngle;
    private RectF mRectF;
    //绘制文字间的分割线
    private Paint mSpiltPaint;

    //渐变的颜色是360度，如果只显示270，那么则会缺失部分颜色
    private SweepGradient mSweepGradient;
    private int[] mGradientColors = {Color.GREEN, Color.YELLOW, Color.RED};
    private int[] mSpiltColors = {0x00FFFFFF, 0xFFFFFFFF};
    //当前进度，[0.0f,1.0f]
    private float mPercent = 0f;
    //动画时间
    private long mAnimTime;
    //属性动画
    private ValueAnimator mAnimator;

    //绘制背景圆弧
    private Paint mBgArcPaint;
    private int mBgArcColor;
    private float mBgArcWidth;

    //圆心坐标，半径
    private Point mCenterPoint;
    private float mRadius;
    private float mTextOffsetPercentInRadius;
    private float currentAngle;

    public CircleProgress(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        mDefaultSize = DensityUtils.dip2px(Constant.DEFAULT_SIZE, mContext);
        mAnimator = new ValueAnimator();
        mRectF = new RectF();
        mCenterPoint = new Point();
        initAttrs(attrs);
        initPaint();
    }

    private void initAttrs(AttributeSet attrs) {
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar);
        antiAlias = typedArray.getBoolean(R.styleable.CircleProgressBar_antiAlias, Constant.ANTI_ALIAS);

        mValue = typedArray.getFloat(R.styleable.CircleProgressBar_value, Constant.DEFAULT_VALUE);
        mMaxValue = typedArray.getFloat(R.styleable.CircleProgressBar_maxValue, Constant.DEFAULT_MAX_VALUE);
        mPrecision = typedArray.getInt(R.styleable.CircleProgressBar_precision, 0);
        mPrecisionFormat = DensityUtils.getPrecisionFormat(mPrecision);
        mValueColor = typedArray.getColor(R.styleable.CircleProgressBar_valueColor, Color.BLACK);
        mValueSize = typedArray.getDimension(R.styleable.CircleProgressBar_valueSize, Constant.DEFAULT_VALUE_SIZE);

        mUnit = typedArray.getString(R.styleable.CircleProgressBar_unit);
        mUnitColor = typedArray.getColor(R.styleable.CircleProgressBar_unitColor, Color.BLACK);
        mUnitSize = typedArray.getDimension(R.styleable.CircleProgressBar_unitSize, Constant.DEFAULT_UNIT_SIZE);

        mArcWidth = typedArray.getDimension(R.styleable.CircleProgressBar_arcWidths, Constant.DEFAULT_ARC_WIDTH);
        mStartAngle = typedArray.getFloat(R.styleable.CircleProgressBar_startAngle, Constant.DEFAULT_START_ANGLE);
        mSweepAngle = typedArray.getFloat(R.styleable.CircleProgressBar_sweepAngle, Constant.DEFAULT_SWEEP_ANGLE);

        mBgArcColor = typedArray.getColor(R.styleable.CircleProgressBar_bgArcColor, Color.WHITE);
        mBgArrowColor = typedArray.getColor(R.styleable.CircleProgressBar_bgArrowColor, Color.WHITE);
        mBgArcWidth = typedArray.getDimension(R.styleable.CircleProgressBar_bgArcWidth, Constant.DEFAULT_ARC_WIDTH);
        mTextOffsetPercentInRadius = typedArray.getFloat(R.styleable.CircleProgressBar_textOffsetPercentInRadius, 0.5f);

        mAnimTime = typedArray.getInt(R.styleable.CircleProgressBar_animTime, Constant.DEFAULT_ANIM_TIME);

        int gradientArcColors = typedArray.getResourceId(R.styleable.CircleProgressBar_arcColors, 0);
        if (gradientArcColors != 0) {
            try {
                int[] gradientColors = getResources().getIntArray(gradientArcColors);
                if (gradientColors.length == 0) {//如果渐变色为数组为0，则尝试以单色读取色值
                    int color = getResources().getColor(gradientArcColors);
                    mGradientColors = new int[2];
                    mGradientColors[0] = color;
                    mGradientColors[1] = color;
                } else if (gradientColors.length == 1) {//如果渐变数组只有一种颜色，默认设为两种相同颜色
                    mGradientColors = new int[2];
                    mGradientColors[0] = gradientColors[0];
                    mGradientColors[1] = gradientColors[0];
                } else {
                    mGradientColors = gradientColors;
                }
            } catch (Resources.NotFoundException e) {
                throw new Resources.NotFoundException("the give resource not found");
            }
        }
        typedArray.recycle();
    }

    private void initPaint() {

        mValuePaint = new TextPaint();
        mValuePaint.setAntiAlias(antiAlias);
        mValuePaint.setTextSize(mValueSize);
        mValuePaint.setColor(mValueColor);
        // 设置Typeface对象，即字体风格，包括粗体，斜体以及衬线体，非衬线体等
        mValuePaint.setTypeface(Typeface.DEFAULT_BOLD);
        mValuePaint.setTextAlign(Paint.Align.CENTER);

        mBgPaint = new Paint();
        mBgPaint.setAntiAlias(antiAlias);
        mBgPaint.setStyle(Paint.Style.FILL);
        mBgPaint.setColor(Color.WHITE);

        mUnitPaint = new TextPaint();
        mUnitPaint.setAntiAlias(antiAlias);
        mUnitPaint.setTextSize(mUnitSize);
        mUnitPaint.setColor(mUnitColor);
        mUnitPaint.setTextAlign(Paint.Align.CENTER);

//        mSpiltPaint = new Paint();
//        mSpiltPaint.setAntiAlias(antiAlias);
//        mSpiltPaint.setStyle(Paint.Style.FILL);

        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(antiAlias);
        mArcPaint.setStyle(Paint.Style.STROKE);
        mArcPaint.setStrokeWidth(mArcWidth);
        mBgArcPaint = new Paint();
        mBgArcPaint.setAntiAlias(antiAlias);
        mBgArcPaint.setColor(mBgArcColor);
        mBgArcPaint.setStyle(Paint.Style.STROKE);
        mBgArcPaint.setStrokeWidth(mBgArcWidth);
        mBgArcPaint.setStrokeCap(Paint.Cap.ROUND);

        mArrowPaint = new Paint();
        mArrowPaint.setAntiAlias(antiAlias);
        mArrowPaint.setStyle(Paint.Style.FILL);
        mArrowPaint.setColor(mBgArrowColor);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(DensityUtils.measure(widthMeasureSpec, mDefaultSize),
                DensityUtils.measure(heightMeasureSpec, mDefaultSize));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        //求圆弧和背景圆弧的最大宽度
        float maxArcWidth = Math.max(mArcWidth, mBgArcWidth);
        //求最小值作为实际值
        int minSize = Math.min(w - getPaddingLeft() - getPaddingRight() - 2 * (int) maxArcWidth,
                h - getPaddingTop() - getPaddingBottom() - 2 * (int) maxArcWidth);
        //减去圆弧弧度
        mRadius = minSize / 2;
        //获取圆的相关参数
        mCenterPoint.x = w / 2;
        mCenterPoint.y = h / 2;
        //绘制圆弧的边界
        mRectF.left = mCenterPoint.x - mRadius - maxArcWidth / 2;
        mRectF.top = mCenterPoint.y - mRadius - maxArcWidth / 2;
        mRectF.right = mCenterPoint.x + mRadius + maxArcWidth / 2;
        mRectF.bottom = mCenterPoint.y + mRadius + maxArcWidth / 2;
        //计算文字绘制时的 baseline
        //由于文字的baseline、descent、ascent等属性只与textSize和typeface有关，所以此时可以直接计算
        //若value、hint、unit由同一个画笔绘制或者需要动态设置文字的大小，则需要在每次更新后再次计算
        mValueOffset = mCenterPoint.y + getBaselineOffsetFromY(mValuePaint) - mRadius * mTextOffsetPercentInRadius / 2;
        mUnitOffset = mCenterPoint.y + mRadius * mTextOffsetPercentInRadius + getBaselineOffsetFromY(mUnitPaint);
        updateArcPaint();
        Log.d(TAG, "onSizeChanged: 控件大小 = " + "(" + w + ", " + h + ")"
                + "圆心坐标 = " + mCenterPoint.toString()
                + ";圆半径 = " + mRadius
                + ";圆的外接矩形 = " + mRectF.toString());
    }

    private float getBaselineOffsetFromY(Paint paint) {
        return DensityUtils.measureTextHeight(paint) / 2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawCircle(canvas);
        drawText(canvas);
        drawArc(canvas);
    }

    private void drawCircle(Canvas canvas) {
        mBgPaint.setStrokeWidth(mRadius + 10);
        canvas.drawCircle(mCenterPoint.x, mCenterPoint.y, mRadius, mBgPaint);
    }


    /**
     * 绘制内容文字
     *
     * @param canvas
     */
    private void drawText(Canvas canvas) {
        if (mValue > 0) {
            canvas.drawText(new BigDecimal(mValue).setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "%", mCenterPoint.x, mValueOffset, mValuePaint);
        } else {
            canvas.drawText("--%", mCenterPoint.x, mValueOffset, mValuePaint);
        }
        if (mUnit != null) {
            canvas.drawText(mUnit.toString(), mCenterPoint.x, mUnitOffset, mUnitPaint);
        }
    }


    private void drawArc(Canvas canvas) {
        currentAngle = mSweepAngle * mPercent;
        //头部圆
        canvas.save();
        canvas.drawArc(mRectF, 0, mSweepAngle, false, mBgArcPaint);
        mArcPaint.setStyle(Paint.Style.FILL);
        currentAngle = 90f - currentAngle; //抵消屏幕坐标系差异
        currentAngle = (float) (Math.PI / 180f * currentAngle);
        float a = mRectF.top,
                b = mRectF.left,
                c = mRectF.width(),
                d = mRectF.height();
        //尾部圆
        canvas.drawCircle(b + c / 2,
                a,
                mArcWidth / 2, mArcPaint);
        canvas.drawCircle((float) (b + c / 2f * (Math.cos(currentAngle) + 1)),
                (float) (a + -1 * d / 2f * (Math.sin(currentAngle) - 1)),
                mArcWidth / 2, mArcPaint);

        // 绘制背景圆弧
        // 从进度圆弧结束的地方开始重新绘制，优化性能
        mArcPaint.setStyle(Paint.Style.STROKE);
        currentAngle = mSweepAngle * mPercent;
        canvas.drawArc(mRectF, 270f, currentAngle, false, mArcPaint);
        currentAngle = 90f - currentAngle; //抵消屏幕坐标系差异
        currentAngle = (float) (Math.PI / 180f * currentAngle);
//        canvas.drawCircle((float) (b + c / 2f * (Math.cos(currentAngle) + 1)),
//                (float) (a + -1 * d / 2f * (Math.sin(currentAngle) - 1)),
//                mBgArcWidth / 2, mArrowPaint);
//        float rl = (float) (mCenterPoint.x - mRadius * 0.8);
//        float rt = (float) (mCenterPoint.y + mRadius * 0.1);
//        float rr = (float) (mCenterPoint.x + mRadius * 0.8);
//        float rb = (float) (mCenterPoint.y + mRadius * 0.15);
//        mSpiltPaint.setShader(new LinearGradient(rl, rt, mCenterPoint.x, rb, mSpiltColors[0], mSpiltColors[1], Shader.TileMode.MIRROR));
//        canvas.drawRect(rl, rt, rr, rb, mSpiltPaint);
        canvas.restore();

    }

    private void updateArcPaint() {
        //设置渐变
        LinearGradient gradient = new LinearGradient(0, 0, getWidth(), getHeight(), mGradientColors[1], mGradientColors[0], Shader.TileMode.CLAMP);
        mArcPaint.setShader(gradient);
    }

    public boolean isAntiAlias() {
        return antiAlias;
    }

    public CharSequence getUnit() {
        return mUnit;
    }

    public void setUnit(CharSequence unit) {
        mUnit = unit;
    }

    public float getValue() {
        return mValue;
    }

    /**
     * 设置当前值
     *
     * @param value
     */
    public void setValue(float value) {
        if (value > mMaxValue) {
            value = mMaxValue;
        }
        float start = 0f;
        float end = value / mMaxValue;
        startAnimator(start, end, mAnimTime);
    }

    private void startAnimator(float start, float end, long animTime) {
        mAnimator = ValueAnimator.ofFloat(start, end);
        mAnimator.setDuration(animTime);
        mAnimator.addUpdateListener(animation -> {
            mPercent = (float) animation.getAnimatedValue();
            mValue = mPercent * mMaxValue;
            if (BuildConfig.DEBUG) {
                Log.d(TAG, "onAnimationUpdate: percent = " + mPercent
                        + ";currentAngle = " + (mSweepAngle * mPercent)
                        + ";value = " + mValue);
            }
            invalidate();
        });
        mAnimator.start();
    }

    /**
     * 获取最大值
     *
     * @return
     */
    public float getMaxValue() {
        return mMaxValue;
    }

    /**
     * 设置最大值
     *
     * @param maxValue
     */
    public void setMaxValue(float maxValue) {
        mMaxValue = maxValue;
    }

    /**
     * 获取精度
     *
     * @return
     */
    public int getPrecision() {
        return mPrecision;
    }

    public void setPrecision(int precision) {
        mPrecision = precision;
        mPrecisionFormat = DensityUtils.getPrecisionFormat(precision);
    }

    public int[] getGradientColors() {
        return mGradientColors;
    }

    /**
     * 设置渐变
     *
     * @param gradientColors
     */
    public void setGradientColors(int[] gradientColors) {
        mGradientColors = gradientColors;
        updateArcPaint();
    }

    public int[] getSpiltColors() {
        return mSpiltColors;
    }

    /**
     * 设置渐变
     *
     * @param spiltColors
     */
    public void setSpiltColors(int[] spiltColors) {
        mSpiltColors = spiltColors;
        updateArcPaint();
    }

    public long getAnimTime() {
        return mAnimTime;
    }

    public void setAnimTime(long animTime) {
        mAnimTime = animTime;
    }

    /**
     * 重置
     */
    public void reset() {
        startAnimator(mPercent, 0.0f, 1000L);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //释放资源
    }
}
